package edu.cque.jt.provider.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import edu.cque.jt.provider.service.ResourceBlockHandler;
import edu.cque.jt.provider.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Hua
 * @create 2022-07-24 16:04
 */
@RestController
@RequestMapping("/provider")
public class ProviderSentinelController {

    @GetMapping("/sentinel01")
    public String doSentinel01(String origin) {
        return "sentinel 01 test"+origin;
    }

    @GetMapping("/sentinel02")
    public String doSentinel02() {
        return "sentinel 02 test";
    }

    @Autowired
    private ResourceService service;

    @GetMapping("/sentinel03")
    public String doSentinel03() {
        return service.doGetResource();

    }

    //构建一个atomicLong对象,提供了线程安全的自增,自减操作
    private AtomicLong atomicLong = new AtomicLong(1);

    @GetMapping("/sentinel04")
    public String doSentinel04() throws InterruptedException {
        long num = atomicLong.getAndIncrement();
        if (num % 2 == 0) {
//            Thread.sleep(2000);//模拟慢调用
//            throw new RuntimeException("timeout");//异常比例
        }
        return "sentinel 04 test";
    }
    @GetMapping("/sentinel/findById")
    @SentinelResource(value = "resource",blockHandlerClass = ResourceBlockHandler.class,blockHandler = "call")
    public String doFindById(@RequestParam("id") Integer id){
        return "resource id is"+id;
    }
}

